<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2006/05/18 22:20:31 $)
// $RCSfile: impex.tickets.php,v $ : $Revision: 1.1 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

require_once ("./modules/tickets/tickets.php");

/**
* Return the Total Pages for this Plugin
*/
function getPluginTotalPages1()
{
	global $impexDB;

	$_total = $impexDB->queryFetch("SELECT COUNT(*) AS totaltickets FROM `ticket`;");
	$finaltotal = intval($_total["totaltickets"]);

	$totalpages = ceil($finaltotal/IMPEX_PASS)+1;

	return $totalpages;
}

/**
* Run the specific page for plugin
*/
function runPluginPage1($page)
{
	global $dbCore, $impexDB, $_IMPEXHASH, $_SWIFT;

	// Import Predefined Replies
	if ($page == 1)
	{
		// Import Predefined Categories
		$predefinedreplies = $predefinedcategories = $catpointer = array();
		$impexDB->query("SELECT * FROM `canned_cat` ORDER BY `id` ASC;");
		while ($impexDB->nextRecord())
		{
			_impexProcessSlashVariables($impexDB->Record);

			$predefinedcategories[$impexDB->Record["id"]] = $impexDB->Record;
		}

		foreach ($predefinedcategories as $key=>$val)
		{
			$predefinedcategoryid = _impexInsertPredefinedCategory(0, $val["category_name"]);
			$catpointer[$key] = $predefinedcategoryid;

			displayStatus("Imported Predefined Category: ".htmlspecialchars($val["category_name"]));
		}

		$impexDB->query("SELECT * FROM `canned_responses` ORDER BY `id` ASC;");
		while ($impexDB->nextRecord())
		{
			_impexProcessSlashVariables($impexDB->Record);

			$predefinedreplies[$impexDB->Record["id"]] = $impexDB->Record;
		}

		foreach ($predefinedreplies as $key=>$val)
		{
			if (isset($catpointer[$val["catid"]]))
			{
				_impexInsertPredefinedReply($catpointer[$val["catid"]], $val["shortname"], $val["template"]);

				displayStatus("Imported Predefined Reply: ".htmlspecialchars($val["shortname"]));
			} else {
				displayStatus("<font color='red'>WARNING:</font> Unable to Import Predefined Reply. Invalid Category ID: ".$val["catid"]);
			}
		}

	// Import Tickets
	} else {
		// Import Tickets! The big tough crap function.
		if (empty($_POST["ticketstartat"]))
		{
			$_startat = 1;
		} else {
			$_startat = intval($_POST["ticketstartat"]);
		}

		$ticketidlist = $ticketlist = $ticketidcharlist = $ticketidpointer = $newticketpointer = array();

		// First get all the tickets
		$impexDB->query("SELECT * FROM `ticket` WHERE `id` >= '". intval($_startat) ."' ORDER BY `id` ASC LIMIT ". intval(IMPEX_PASS) .";");
		while ($impexDB->nextRecord())
		{
			_impexProcessSlashVariables($impexDB->Record);

			$ticketidlist[] = $impexDB->Record["id"];
			$ticketidcharlist[] = $impexDB->Record["id"];
			$ticketidpointer[$impexDB->Record["id"]] = $impexDB->Record["id"];
			$ticketlist[$impexDB->Record["id"]] = $impexDB->Record;
			$ticketlist[$impexDB->Record["id"]]["posts"] = array();
			$lastticketid = $impexDB->Record["id"];
		}

		// Now load in stuff from asTicketReply table
		$impexDB->query("SELECT * FROM `reply` WHERE `ticketid` IN (". buildIN($ticketidlist) .");");
		while ($impexDB->nextRecord())
		{
			_impexProcessSlashVariables($impexDB->Record);

			$ticketidno = $impexDB->Record["ticketid"];
			$_ticket = &$ticketlist[$ticketidno];
			$_ticket["posts"][$impexDB->Record["id"]] = $impexDB->Record;
		}

		// By now, almost all data should be loaded.. insert the tickets first
		foreach ($ticketlist as $key=>$val)
		{
			$newdepartmentid = intval($_IMPEXHASH["departmentpointer"][$val["category"]]);
			if (empty($newdepartmentid))
			{
				$newdepartmentid = $_IMPEXHASH["firstdepartment"];
			}

			if ($val["is_open"] == 1)
			{
				$_ticketstatus = 1;
			} else if ($val["awaiting_reply"] == 1) {
				$_ticketstatus = 2;
			} else {
				$_ticketstatus = 3;
			}

			$ticketid = _impexInsertTicket($val["id"], $newdepartmentid, $_ticketstatus, 1, "0", "0", "0", intval($_IMPEXHASH["staffpointer"][$val["admin_owner"]]), $val["email"], $val["email"], $val["last_reply"], $val["subject"], $val["date_started"], $val["date_reply"], count($val["posts"]), POST_CLIENT);

			$firstpostid = $lastpostid = 0;

			foreach ($val["posts"] as $postkey=>$postval)
			{
				if (empty($postval["admin_id"]))
				{
					$_postemail = $val["email"];
					$_postname = $_postemail;
					$_type = "customer";
				} else {
					$_postemail = $_IMPEXHASH["staffemailpointer"][$postval["admin_id"]];
					if (!empty($_IMPEXHASH["staffnamepointer"][$postval["admin_id"]]))
					{
						$_postname = $_IMPEXHASH["staffnamepointer"][$postval["admin_id"]];
					} else {
						$_postname = $_IMPEXHASH["staffemailpointer"][$postval["admin_id"]];
					}
					$_type = "staff";

					// Staff details are empty, fill em up with customers
					if (empty($_postemail) && !empty($_postname))
					{
						$_postemail = $_postname;
					} else if (empty($_postemail)) {
						$_postemail = $val["email"];
						$_postname = $_postemail;
						$_type = "customer";
					}
				}
				$_ticketpostid = _impexInsertTicketPost($ticketid, $postval["date"], "0", $_postname, $_postemail, "", $val["subject"], $postval["ipaddress"], iif($_type=="customer", POST_CLIENT, POST_STAFF), 0, 0, $postval["message"]);
				$lastreplier = $_postname;
				if (empty($firstpostid))
				{
					$firstpostid = $_ticketpostid;
				}
				$lastpostid = $_ticketpostid;
			}

			$dbCore->query("UPDATE `". TABLE_PREFIX ."tickets` SET `lastreplier` = '". $dbCore->escape(iif(empty($lastreplier), $val["email"], $lastreplier)) ."', `firstpostid` = '". intval($firstpostid) ."', `lastpostid` = '". intval($lastpostid) ."' WHERE `ticketid` = '". intval($ticketid) ."';");
			$newticketpointer[$val["ticketid"]] = $ticketid;

			displayStatus("Imported Ticket: ".$val["id"]);

		}

		unset($ticketlist);

		$_SWIFT["ticketstartat"] = $lastticketid+1;
	}
}
?>